package com.net.wanjian.networkhospitalmanager.activity.evaluate;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.adapter.EvaluateEventHomeAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.SearchEvaluateResult;
import com.net.wanjian.networkhospitalmanager.consts.AppConsts;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.fragment.base.BaseFragment;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.view.NoDataEmptyView;
import com.net.wanjian.networkhospitalmanager.widge.RefreshRecyclerView;

import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link EvaluateListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class EvaluateListFragment extends BaseFragment {
    private static final String EVALUATE_TYPE = "evaluate_type";
    public static final String REFRESH_SIMPLE_EVALUATE_LIST = "com.net.wanjian.activity.evaluate.evaluatelistfragment.refresh_simple_evaluate_list";
    @BindView(R.id.evaluate_reserve_recycler_view)
    RefreshRecyclerView evaluateReserveRecyclerView;
    @BindView(R.id.evaluate_lab_no_data_layout)
    NoDataEmptyView evaluateLabNoDataLayout;

    private String evaluateType;
    private int currentNum = AppConsts.currentPageNum, currentPageNum, countNum;
    private EvaluateEventHomeAdapter evaluateEventHomeAdapter;
    private List<SearchEvaluateResult.DataBean.EventListBean> mEventList;
    private LocalBroadcastManager localBroadcastManager;

    public EvaluateListFragment() {

    }

    /**
     * @param type 事件类型
     * @return
     */
    public static EvaluateListFragment newInstance(String type) {
        EvaluateListFragment fragment = new EvaluateListFragment();
        Bundle args = new Bundle();
        args.putString(EVALUATE_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            evaluateType = getArguments().getString(EVALUATE_TYPE);
        }
    }


    @Override
    protected void initView() {

        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        IntentFilter filter = new IntentFilter();
        filter.addAction(REFRESH_SIMPLE_EVALUATE_LIST);
        localBroadcastManager.registerReceiver(receiver, filter);

        evaluateLabNoDataLayout.setNoData(R.string.no_evaluate);
        evaluateLabNoDataLayout.setOnReLoadClickListener(new NoDataEmptyView.OnReLoadClickListener() {
            @Override
            public void onReloadClick(View v) {
                //这里根据evaluateType请求数据
                getEvaluateDataHttpRequest();
            }
        });

        evaluateReserveRecyclerView.setRefreshMode(3);
        evaluateReserveRecyclerView.addOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //这里根据evaluateType请求数据
                getEvaluateDataHttpRequest();
            }

            @Override
            public void onLoadMore() {
                loadMore();
            }
        });

        evaluateReserveRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        getFirstEvaluateDataHttpRequest();
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        currentPageNum++;
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchHistoryEventList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getUserIdentity(), evaluateType, currentPageNum, currentNum, new DisposableObserver<SearchEvaluateResult>() {
                    @Override
                    public void onNext(SearchEvaluateResult searchEvaluateResult) {
                        if (searchEvaluateResult.getResult() == ErrorCodeReturn.success) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchEvaluateResult.getData().getToken()));
                            List<SearchEvaluateResult.DataBean.EventListBean> eventList = searchEvaluateResult.getData().getEventList();
                            mEventList.addAll(eventList);
                            evaluateEventHomeAdapter.setList(mEventList);

                            if (eventList.size() < currentNum || mEventList.size() >= countNum) {
                                evaluateReserveRecyclerView.setNoMore(true);
                            } else {
                                evaluateReserveRecyclerView.loadMoreComplete();
                            }

                        } else {
                            evaluateReserveRecyclerView.loadMoreComplete();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        evaluateReserveRecyclerView.loadMoreComplete();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 第一次进入获取历史事件列表，根据条件
     */
    private void getFirstEvaluateDataHttpRequest() {
        ProgressDialogUtils.showProgressDialog(mContext, "", R.string.loading_text);
        //这里获取网络数据
        currentPageNum = 0;
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchHistoryEventList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getUserIdentity(), evaluateType, currentPageNum, currentNum, new DisposableObserver<SearchEvaluateResult>() {
                    @Override
                    public void onNext(SearchEvaluateResult searchEvaluateResult) {
                        if (searchEvaluateResult.getResult() == ErrorCodeReturn.success) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchEvaluateResult.getData().getToken()));

                            int deepNum = Integer.parseInt(URLDecoderUtil.getDecoder(searchEvaluateResult.getData().getEventUnEvaluatedDeepTableNum()));
                            int simpleNum = Integer.parseInt(URLDecoderUtil.getDecoder(searchEvaluateResult.getData().getEventUnEvaluatedSimpleTableNum()));
                            ((HistoryEventEvaluateActivity) getActivity()).setWaitEvaluateView(simpleNum, deepNum);

                            mEventList = searchEvaluateResult.getData().getEventList();

                            countNum = Integer.parseInt(searchEvaluateResult.getData().getTotalCount());

                            evaluateEventHomeAdapter = new EvaluateEventHomeAdapter(mContext);
                            evaluateEventHomeAdapter.setList(mEventList);
                            evaluateReserveRecyclerView.setAdapter(evaluateEventHomeAdapter);

                            evaluateEventHomeAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(int pos) {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(EvaluateDetailsActivity.EVALUATEDETAILSACTIVITY_EVENT_KEY,mEventList.get(pos));
                                    openActivity(EvaluateDetailsActivity.class, bundle);
                                }
                            });

                            if (searchEvaluateResult.getData().getEventList().size() < currentNum || mEventList.size() >= countNum) {
                                evaluateReserveRecyclerView.setNoMore(true);
                            } else {
                                evaluateReserveRecyclerView.setNoMore(false);
                            }
                        }
                        evaluateReserveRecyclerView.setEmptyView(evaluateLabNoDataLayout);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });

//        evaluateReserveRecyclerView.refreshComplete();
//
//        initRecyclerList();
    }

    /**
     * 获取历史事件列表，根据条件
     */
    private void getEvaluateDataHttpRequest() {
        //这里获取网络数据
        currentPageNum = 0;
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchHistoryEventList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getUserIdentity(), evaluateType, currentPageNum, currentNum, new DisposableObserver<SearchEvaluateResult>() {
                    @Override
                    public void onNext(SearchEvaluateResult searchEvaluateResult) {
                        if (searchEvaluateResult.getResult() == ErrorCodeReturn.success) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchEvaluateResult.getData().getToken()));

                            int deepNum = Integer.parseInt(URLDecoderUtil.getDecoder(searchEvaluateResult.getData().getEventUnEvaluatedDeepTableNum()));
                            int simpleNum = Integer.parseInt(URLDecoderUtil.getDecoder(searchEvaluateResult.getData().getEventUnEvaluatedSimpleTableNum()));
                            ((HistoryEventEvaluateActivity) getActivity()).setWaitEvaluateView(simpleNum, deepNum);

                            mEventList = searchEvaluateResult.getData().getEventList();

                            countNum = Integer.parseInt(searchEvaluateResult.getData().getTotalCount());

                                evaluateEventHomeAdapter.setList(mEventList);

                            if (searchEvaluateResult.getData().getEventList().size() < currentNum || mEventList.size() >= countNum) {
                                evaluateReserveRecyclerView.refreshComplete();
                                evaluateReserveRecyclerView.setNoMore(true);
                            } else {
                                evaluateReserveRecyclerView.refreshComplete();
                                evaluateReserveRecyclerView.setNoMore(false);
                            }
                        } else {
                            evaluateReserveRecyclerView.refreshComplete();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        evaluateReserveRecyclerView.refreshComplete();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

//        evaluateReserveRecyclerView.refreshComplete();
//
//        initRecyclerList();
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        evaluateLabNoDataLayout.setNoData(R.string.no_evaluate);
        evaluateReserveRecyclerView.setEmptyView(evaluateLabNoDataLayout);
//        getEvaluateDataHttpRequest();
    }

    @Override
    protected void onNetworkDisConnected() {

        //清空集合数据
        mEventList.clear();

        evaluateLabNoDataLayout.setNoNetWork();
        evaluateReserveRecyclerView.setEmptyView(evaluateLabNoDataLayout);
        evaluateEventHomeAdapter.notifyDataSetChanged();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_evaluate_list;
    }

    @Override
    protected void initData() {

    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (REFRESH_SIMPLE_EVALUATE_LIST.equals(intent.getAction())) {
                evaluateReserveRecyclerView.refresh();
            }
        }
    };

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(receiver);
        super.onDestroy();
    }
}
